import { router, addRoutes } from './index.ts'
import { getToken } from '@/core/utils/auth'
import { ElNotification } from 'element-plus'
import { showFullLoading, hideFullLoading } from '@/core/utils/tools'
import store from '@/core/stores'
// 全局前置守卫
let hasGetInfo = false
router.beforeEach(async (to, from, next) => {
  showFullLoading()
  const token = getToken()

  // 如果没有token 则跳转到登录页
  if (!token && to.path !== '/login') {
    ElNotification({ message: '请先登录', type: 'error' })
    return next('/login')
  }
  // 防止用户重复登录
  if (token && to.path === '/login') {
    ElNotification({ message: '请勿重复登录' })
    return next({ path: from.path ?? '/' })
  }

  // 如果用户登录了，自动获取用户信息，并存储在vuex当中
  let hasNewRoutes = false
  if (token && !hasGetInfo) {
    const { menus } = await store.dispatch('getinfo')

    hasGetInfo = true
    // 动态添加路由
    hasNewRoutes = addRoutes(menus)
  }

  // 设置页面标题
  const title = (to.meta.title ? to.meta.title : '') + '后台管理'
  document.title = title
  hasNewRoutes ? next(to.fullPath) : next()
})

// 全局后置守卫
router.afterEach(() => {
  hideFullLoading()
})
